<template>
    <div class="groupManage-container">
        <ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" @expand="expandHandle" />

        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select-all="onSelectAll"
            @selection-change="onSelect">
            <template #headerOperateLeft>
                <div class="left">最近一次同步时间为:{{ updateTime }}</div>
            </template>
            <template #headerOperate>
                <div class="gc-content">
                    <div class="right">
                        <el-button :disabled="chooseTableData.length == 0" @click="openBatchLabel('batch')">
                            批量打标/移除
                        </el-button>
                        <el-button v-auth="'SYNC_WECOM'" :icon="RefreshRight" @click="handleSynchronization">
                            同步企微客户群
                        </el-button>
                    </div>
                </div>
            </template>
        </ZwTable>
        <!-- 创建人弹框 -->
        <ZWDepart ref="DepartRef" @submit="getDepart"></ZWDepart>
        <!-- 批量标签弹框 -->
        <BatchLabel ref="BatchLabelRef" path="/customer/client/clientList" @save="getTagsFun" />
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CUSTOMER_GROUPMANAGE_LIST' });
</script>

<script lang="tsx" setup>
import { reactive, ref, onMounted, computed, onActivated } from 'vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Dialog from '@/components/Dialog.vue';
import ZWDrawer from '@/components/ZWDrawer.vue';
import BatchLabel from '@/components/BatchLabel.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import { getGroupManageList, syncGroupManage } from '@/api/groupManageList';
import { RefreshRight, Plus, ArrowDownBold, ArrowUpBold } from '@element-plus/icons-vue';
import { useStore } from '@/store';
import { getSyncTime, custSyncResult } from '@/api/customerCenter/groupManage';
import { batchAddGroupTag, batchGroupRmTag } from '@/api/customerCenter';

import { ElMessage, ElImage, ElIcon, ElPopover, ElTag, ElButton, ElLoading } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';

import { deepCopy } from '@/utils/helper';

import { AFold, tableH, getSetionId, reSize } from '@/utils/utils';
import { parabolaAnimation } from '@/utils/parabola';

import router from '@/router';
import dayjs from 'dayjs';

const store = useStore();
const tableRef = ref();
const BatchLabelRef = ref(null);
const tabsList = ref([]);
const chooseTableData = ref([]);
const updateTime = ref('');
const creators = ref([]);
const DepartRef = ref(null);
const multipleTableRef = ref<any>(null);
const formInline = reactive({
    select_tag_type: 0,
    is_qw_group: '-1',
    group_leader: [],
    group_name: '',
    groupchat_tag_list: []
});

const pageInfo = reactive({
    page_size: 15,
    page: 1
});

const total = ref(0);
const tabH = ref('400px');

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const defaultParams = reactive({
    is_qw_group: '-1',
    group_leader: [],
    groupchat_tag_list: [],
    group_name: ''
});
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '是否企微群',
            name: 'is_qw_group',
            type: 'select',
            clearable: false,
            placeholder: '请选择是否企微群',
            optionList: [
                { name: '全部', id: '-1' },
                { name: '企微群', id: '1' },
                { name: '非企微群', id: '0' }
            ],
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '群主/创建人',
            name: 'group_leader',
            value: [],
            multiple: true,
            type: 'select',
            placeholder: '请选择',
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '群名称',
            name: 'group_name',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入群名称搜索',
            isKeyupEnter: true
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        label: '群信息',
        minWidth: 200,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image_slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <div class="groupInfo">
                    <ElImage vSlots={{ error: slotError }} src={row.avatar} fit="cover" class="group_avatar"></ElImage>
                    <span>{row.name}</span>
                </div>
            );
        }
    },
    {
        prop: 'groupchat_tag',
        label: '客户群标签',
        width: 300,
        isTag: true
    },
    {
        label: '是否企微群',
        width: 130,
        render({ row, column, index }) {
            return <p>{row.is_wx_group ? '是' : '否'}</p>;
        }
    },
    {
        prop: 'members_num',
        label: '群人数',
        width: 100
    },
    {
        prop: 'manager',
        label: '群主/创建人',
        width: 160,
        render({ row }) {
            return (
                <>
                    <div vShow={row.manager.name}>
                        <span vShow={row.manager.name}> {row.manager.name}/</span>
                        <span vShow={!row.manager.name}>-/</span>
                        {row.manager.department_name.map((item: any) => {
                            return <span>{item.name || '--'}</span>;
                        })}
                    </div>
                    <div vShow={!row.manager.name}>暂无</div>
                </>
            );
        }
    },
    {
        label: '协助员工',
        minWidth: 300,
        render({ row, column, index }) {
            const slotReference = () => (
                <div vShow={row.staff_list.length != 0} class="assist">
                    {row.staff_list.map((item: any) => {
                        return (
                            <span>
                                {item.name}/{item.department_name}
                            </span>
                        );
                    })}
                </div>
            );
            const slotDefault = () => (
                <div vShow={row.staff_list.length != 0}>
                    {row.staff_list.map((item: any) => {
                        return (
                            <span>
                                {item.name}/{item.department_name}
                            </span>
                        );
                    })}
                </div>
            );
            return (
                <>
                    <ElPopover
                        vShow={row.staff_list && row.staff_list.length != 0}
                        popper-class="popGroup"
                        trigger="hover"
                        vSlots={{ reference: slotReference, default: slotDefault }}
                        width={300}
                        popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    <span vShow={row.staff_list.length <= 0}>--</span>
                </>
            );
        }
    },
    {
        prop: 'work_wx_members_num',
        label: '企微客户人数',
        width: 140
    },
    {
        prop: 'create_type_text',
        label: '创建方式',
        width: 130
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 190,
        render({ row }) {
            return <span>{dayjs(row.created_at).format('YYYY-MM-DD HH:mm:ss')}</span>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 110,
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton size="small" vAuth={'VIEW_DETAIL'} onClick={() => handleDetails(index, row)}>
                        详情
                    </ElButton>
                </div>
            );
        }
    }
];
const getRowKey = (row: any) => {
    return row.id;
};
const search = (data: any) => {
    currentParams.value = data;
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy({ ...defaultParams, ...data });
};
const reset = (v?: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy(defaultParams);
    currentParams.value = null;
};
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};
const fetchApi = () => {
    // 获取文件列表
    // getTableH()
    return getGroupManageList;
};
// 表格的自适应高度
const getTableH = () => {
    // tabH.value = tableH('.table-box')
};

// 选中表格 checkbox
const onSelect = (selection: any) => {
    chooseTableData.value = selection;
};
// 全选
const onSelectAll = (selection: any) => {
    chooseTableData.value = selection;
};

const visible = ref(true);
const pickUp = () => {
    visible.value = !visible.value;
    AFold(visible.value, '.el_filter_row');
    getTableH();
};

const handleDetails = (index: number, row: any) => {
    router.push({
        path: '/customer/groupManage/list/detail',
        query: { id: row.group_id }
    });
};

const tableData = ref([]);
let timeId: any = '';
let loading: any = '';
const checkSuccessSync = (jobid: string) => {
    custSyncResult({ jobid, type: 2 }).then((r: any) => {
        loading = ElLoading.service({
            lock: true,
            text: '同步中....',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        if (!r) {
            loading.close();
            clearInterval(timeId);
            getSyncTimeFun();
            fetch();
            timeId = '';
            ElMessage.error('同步失败');
            return;
        }
        if (r.status > 1) {
            loading.close();
            clearInterval(timeId);
            getSyncTimeFun();
            fetch();
            ElMessage[r.status == 2 ? 'success' : 'error'](r.status == 2 ? '同步成功' : '同步失败');
            timeId = '';
            if (r.status == 2) {
                tableRef.value?.clearSelection();
            }
        } else {
            if (!timeId) {
                timeId = setInterval(() => {
                    checkSuccessSync(jobid);
                }, 3000);
            }
        }
    });
};
// 同步企微客户
const handleSynchronization = () => {
    syncGroupManage({}).then((res: any) => {
        checkSuccessSync(res.jobid);
    });
};
const labelObj = {
    type: '', //当前打开选择标签是哪个类型
    data: [] //选中标签的数据存储
};
//切换标签
const changeLabel = (value: any) => {
    if (!value.length) {
        formInline.select_tag_type = 0;
    }
    tabsList.value = tabsList.value.filter((item: any) => value.includes(item.id));
};
// 打开选择标签弹框
const openBatchLabel = (type: string) => {
    labelObj.type = type;
    if (type == 'formData') BatchLabelRef.value.title = '群标签';
    BatchLabelRef.value.dialogData.labelChooseType = type == 'formData' ? 2 : 1;
    BatchLabelRef.value.chooseDataArr = [];
    BatchLabelRef.value.hasConditiion = type == 'formData' ? false : true;
    if (tabsList.value.length > 0 && type == 'formData') {
        BatchLabelRef.value.chooseDataArr = tabsList.value;
    }
    BatchLabelRef.value.type = false;
    BatchLabelRef.value.dialogVisible = true;
};
// 获取当前选中的标签数据
const getTagsFun = (val: any) => {
    if (labelObj.type == 'formData') {
        formInline.groupchat_tag_list = val.idList;
        //  0: 无标签，1：满足任意一个标签， 2：同时满足所有标签
        formInline.select_tag_type = val.idList.length > 0 ? val.labelType : 0;
        tabsList.value = val.data;
        return;
    }
    const id = [];
    chooseTableData.value.forEach((item: any) => {
        id.push(item.group_id);
    });
    const param = {
        groupchat_list: id,
        groupchat_tag_list: val.idList
    };
    //  3批量打标签  4 批量删除标签
    if (val.labelType == 3) {
        batchAddTagFun(param);
        return;
    }
    batchRmTagFun(param);
};
// 批量打标签
const batchAddTagFun = (param: object) => {
    batchAddGroupTag(param).then((r: object) => {
        tableRef.value.reload();
        tableRef.value?.clearSelection();
        chooseTableData.value = [];
    });
};
// 批量删除标签
const batchRmTagFun = (param: object) => {
    batchGroupRmTag(param).then((r: object) => {
        tableRef.value.reload();
        tableRef.value?.clearSelection();
        chooseTableData.value = [];
    });
};
const handleAdd = () => {};

// 查询列表数据
const fetch = () => {
    getGroupManageList({
        ...pageInfo,
        ...formInline
    }).then((res: any) => {
        tableData.value = res.data;
        total.value = res.total;
        store.dispatch('pageTotal', res.total);
    });
};
const getSyncTimeFun = () => {
    getSyncTime({ sync_type: 110 }).then((r: any) => {
        updateTime.value = r.weiwork_synctime;
    });
};
getSyncTimeFun();

// 分页信息
const page = (page: any) => {
    pageInfo.page = page.page;
    pageInfo.page_size = page.page_size;
    fetch();
};

// 搜索查询
const onSubmit = () => {
    multipleTableRef.value!.clearSelection();
    fetch();
};

// 清空查询表单
const onClear = () => {
    formInline.is_qw_group = '-1';
    formInline.group_leader = [];
    formInline.group_name = '';
    formInline.groupchat_tag_list = [];
    formInline.select_tag_type = 0;
    pageInfo.page = 1;
    creators.value = [];
    tabsList.value = [];
    BatchLabelRef.value.chooseDataArr = [];
    pageInfo.page_size = 15;
    multipleTableRef.value!.clearSelection();
    fetch();
};
const SelectionChange = (val: any) => {
    chooseTableData.value = val;
};
onMounted(() => {
    getTableH();
    reSize(getTableH);
});
//打开员工弹窗
const opendept = (data: any) => {
    DepartRef.value.selectedMember = creators.value;
    // DepartRef.value.depart = DepartRef.value.clean(DepartRef.value.depart)
    // data.forEach((item: any) => {
    //   DepartRef.value.leftchecktree(item.id)
    // })
    DepartRef.value.departVisble = true;
};
const getDepart = (res: any) => {
    creators.value = res;
    formInline.group_leader = [];
    creators.value.forEach((item: any, index: any) => {
        formInline.group_leader[index] = item.id;
    });
    DepartRef.value.departVisble = false;
};
//删除选择的创建人
const changedept = (res: any) => {
    const removeDepart = creators.value.find((item: any) => !res.includes(item.id));
    creators.value = creators.value.filter((data: any) => res.includes(data.id));
    formInline.group_leader = res;
    DepartRef.value.removeItem(removeDepart);
};

onActivated((val: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>

<style scoped lang="scss">
.groupManage-container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.gc-header {
    background-color: #f9f9f9;
    padding: 16px 24px;
    margin-bottom: 10px;

    .help_icon {
        cursor: pointer;
        width: 14px;
        height: 14px;
        margin: 12px 10px 0 2px;
    }

    .el-row {
        display: flex;
        flex-wrap: wrap;
        position: relative;
        box-sizing: border-box;
        margin: -8px -10px;

        .el-col {
            margin: 8px 0;

            &:last-of-type {
                flex: auto;
                text-align: right;
            }

            .el-form-item {
                margin-bottom: 0;
                width: 100%;

                .el-form-item__label-wrap {
                    .el-form-item__label {
                        font-size: 14px;
                        font-family: STHeitiSC-Light, STHeitiSC;
                        font-weight: 300;
                        color: #33302d;
                    }
                }

                :deep .el-form-item__content {
                    margin-left: 0 !important;

                    .help_icon {
                        margin-right: 14px;
                    }

                    .el-input,
                    .el-select,
                    .el-date-editor {
                        width: 100%;
                    }
                }
            }
        }
    }

    .btn {
        float: right;
    }

    .el-form-item {
        margin-bottom: 0;
    }
}

.btn-wrap {
    display: flex;
}

.zw_table {
    margin: 0;
}

.tag_box {
    display: flex;
    display: -webkit-box; //谷歌
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1; //显示几行
    overflow: hidden;
}

.form-tags {
    margin: 0 10px 0 0;
}

.table-box {
    :deep(.groupInfo) {
        display: flex;
        align-items: center;
        color: #33302d;

        .group_avatar {
            width: 36px;
            height: 36px;
            border-radius: 4px;
            margin-right: 10px;
        }
    }
}

:deep(.assist) {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
}
</style>
